<?php
/**
 * Created by PhpStorm.
 * User: DR
 * Date: 2018/8/5
 * Time: 11:40
 */

namespace app\api\controller;


use app\common\controller\Api;
use app\api\model\User;
use app\api\model\Deal as DealModel;
use app\common\model\Order;
use EasyWeChat\Support\Log;
use think\Db;
use think\Exception;
use think\exception\DbException;

/*
 * 交易转账接口
 */

class Deal extends Api
{
    protected $data = '';
    protected $user = '';
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $failException = true;

    /*
     *验证支付密码
     * @param string $token 用户token
     * @param string $pay_password  用户密码
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->data = $this->request->request();
        $rule = [
            'pay_password' => 'require',
        ];
        $this->validate($this->data, $rule);
        $this->user = $this->auth->getUser();
        $pay_password = $this->auth->getEncryptPassword($this->data['pay_password'], $this->user->salt);
        if ($this->user->pay_password != $pay_password) {
            $this->error('支付密码不正确');
        }
//        if(!$this->user->is_certification)
//        {
//            $this->error('未实名无法交易');
//        }
    }

    /*
     * 买卖挂单
     * @param int $cny  挂的cny数量
     * @param int $type 是买入还是卖出 0=买入 1=卖出
     */
    public function makeDeal()
    {
        $rule = [
            'cny' => 'require|integer',
            'type' => 'require|in:0,1',
        ];
        $this->validate($this->data,$rule);
        $this->data['remark'] = $this->request->request('remark') ? $this->request->request('remark') : '';
        if (strlen($this->data['remark']) > 100)
        {
            $this->error('备注最长100字');
        }
        $this->checkCny($this->data['cny']);
        DealModel::makeDeal($this->user,$this->data);
        $this->success('挂单成功!');
    }

    /*
     * 转账
     * @param int $targe_id 转账人ID
     * @param int $targe_mobile 转账人手机
     * @param int $cny 转账的cny
     */
    public function transfer()
    {
        $rule = [
            'transfer_id' => 'require|integer',
            'transfer_mobile' => 'require',
            'cny' => 'require|integer',
        ];
        $this->validate($this->data, $rule);
        if ($this->user->cny < $this->data['cny']) {
            $this->error('账户余额不足');
        }
        $this->checkCny($this->data['cny']);
        $userModel = new User();
        $where = [
            'id' => $this->data['transfer_id'],
            'mobile' => $this->data['transfer_mobile'],
        ];
        $transfer = $userModel->where($where)
            ->find();
        if (!$transfer) {
            $this->error('转账用户不存在');
        }
        User::targeCny($this->user, $transfer, $this->data['cny']);
        $this->success('转账成功!');
    }

    /*
     * 验证cny是否是100的倍数
     * @param int $cny
     */
    protected function checkCny($cny)
    {
        $multiple = config('multiple');
        if ($cny % $multiple !== 0) {
            $this->error('必须交易'.$multiple.'的倍数');
        }
        if ($cny <= 0) {
            $this->error('输入金额不正确!');
        }
    }


    /**
     * 确认付币
     */
    public function confirm_pay_coin()
    {
        $order_sn = $this->request->request('order_sn');

        if (!$order_sn)
        {
            $this->error('订单号不能为空');
        }

        $user = $this->auth->getUser();

        $order = new Order();
        $order_where = [
            'order_sn' => $order_sn,
            'sale_user_id'  =>  $user->id,
            'status' => '2'
        ];

        //  订单信息
        $order_info = $order->where($order_where)->find();
        if (!$order_info)
        {
            $this->error('订单不存在');
        }

        //  买家信息
        $buy_user =  User::get($order_info->buy_user_id);
        if (!$buy_user)
        {
            $this->error('买家不存在');
        }
        $buy_user_update = [
            'cny'       =>  $buy_user->cny + $order_info->cny,
            'total_cny' =>  $buy_user->total_cny + $order_info->cny
        ];



        //  事务提交
        Db::startTrans();
        try{
            $order_info->save(['status' => config('OrderStatus.Finished'),'complete_time' => time()]);    //  更新当笔交易状态
            $user->save(['freeze_cny' => $user->freeze_cny - $order_info->cny]);    //  更新卖家币数
            $buy_user->save($buy_user_update);  //  更新买家币数
            //  记录资金流动
            account_log($user->id,'',$user->cny + $user->freeze_cny,0,$user->sac,'卖家ID'.$user->id.'确认付币'.$order_info->cny,$order_info->cny * -1,$order_info->sale_deal_sn);
            account_log($buy_user->id,$order_info->cny,$buy_user->cny + $buy_user->freeze_cny,0,$buy_user->sac,'买家ID'.$buy_user->id.'收币'.$order_info->cny,'',$order_info->buy_deal_sn);
            //  判断是否修改交易标状态
            $deal_finish_status = ['status' => config('DealStatus.Finished'),'complate_time' => time()];

            //  查找是否还有未完成记录
            $buy_finished = $order->where([
                'buy_deal_sn' => $order_info->buy_deal_sn,
                'status' => ['<>', config('OrderStatus.Finished')]
            ])->find();
            $sale_finished = $order->where([
                'sale_deal_sn'  =>  $order_info->sale_deal_sn,
                'status'    =>  ['<>' , config('OrderStatus.Finished')]
            ])->find();
            if (empty($buy_finished))
            {
                $deal_info = DealModel::get(['deal_sn' => $order_info->buy_deal_sn]);
                if($deal_info && $deal_info->residue_cny <= 0){
                    $deal_info->save($deal_finish_status);
                }
            }
            if (empty($sale_finished))
            {
                $deal_info = DealModel::get(['deal_sn' => $order_info->sale_deal_sn]);
                if ($deal_info && $deal_info->residue_cny <= 0)
                {
                    $deal_info->save($deal_finish_status);
                }
            }

            //  确认付币给买家发送短信
            send_common_sms($buy_user->mobile,$order_info->order_sn,'已成功交易');
            send_common_sms($user->mobile,$order_info->order_sn,'已成功交易');   //  卖家点确认卖家发送信息

            Db::commit();
        }catch (Exception $e)
        {
            Db::rollback();
            Log::error($e);
        }
        $this->success('付币成功');
    }

}